import Vue from 'vue'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { USER_ID, INDEX_MAIN_PAGE_PATH, ACCESS_TOKEN } from '@/store/mutation-types'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/register', '/user/register-result'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  // NProgress.start() // start progress bar
  if (Vue.ls.get(ACCESS_TOKEN)) {
    if (to.path === '/' || to.path === '/login') {
      next({ path: '/sys/role' })
      NProgress.done()
    } else {
      if (store.getters.menus.length === 0) {
        store.dispatch('GetMenuList').then(res => {
          next()
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next({ path: '/login' })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
